﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using System.Xml;
using System.Text;
using Windows.Data.Xml.Dom;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using System.Collections;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.Storage.Pickers;
using System.Xml.Serialization;
using System.Runtime.Serialization;
using Windows.UI.Xaml.Media.Animation;
using Windows.UI.Popups;

// The Basic Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234237

namespace StudyTime_1
{
    /// <summary>
    /// A basic page that provides characteristics common to most applications.
    /// </summary>
    public sealed partial class quizBuilder1 : StudyTime_1.Common.LayoutAwarePage
    {

        public List<quizQuest> quizList = new List<quizQuest>();
        private bool saveLocation = false;
        private string filePath;
        private string fileName = "goo.xml";
        private StorageFile storage;
        private StorageFile tempStorage;
        private byte[] img;
        private Stream outStream;
        private DataContractSerializer xml;
        private bool showMessage = false;
        private bool quizLoaded = false;

        public quizBuilder1()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
        }

        /// <summary>
        /// Preserves state associated with this page in case the application is suspended or the
        /// page is discarded from the navigation cache.  Values must conform to the serialization
        /// requirements of <see cref="SuspensionManager.SessionState"/>.
        /// </summary>
        /// <param name="pageState">An empty dictionary to be populated with serializable state.</param>
        protected override void SaveState(Dictionary<String, Object> pageState)
        {
        }

        async private void loadData(List<quizQuest> quiz)
        {

            //convLength = 0;

            quizList.Clear();
           
            {

                StorageFolder storageFolder = KnownFolders.VideosLibrary;



                {
                    try
                    {
                        errorBox.Text = fileName;
                        //Opens the text file that the array is stored in.
                        // storage = await storageFolder.GetFileAsync(filePath);




                         xml = new DataContractSerializer(typeof(List<quizQuest>));

                        var file = await storage.OpenAsync(FileAccessMode.Read);
                        Stream inStream = file.AsStreamForRead();

                        quiz = xml.ReadObject(inStream) as List<quizQuest>;

                        foreach (quizQuest quizQuest in quiz)
                        {
                            quizList.Add(quizQuest);
                        }


                        if (showMessage == false)
                        {
                            var mDialog = new MessageDialog("Since you opened a file, adding a quiz will append to the opened file, there is no need to save again. But the button remains for your comfort.");
                            await mDialog.ShowAsync();
                            showMessage = true;
                            quizLoaded = true;
                            saveAll.IsEnabled = true;
                            
                        }
                        else
                        {
                        }

                   
                    }
                    catch (IOException)
                    {

                    }
                }
            }
        }

        async public void openSelected()
        {
            FileOpenPicker openPicker = new FileOpenPicker();
            openPicker.ViewMode = PickerViewMode.List;
            openPicker.SuggestedStartLocation = PickerLocationId.Downloads;
            openPicker.FileTypeFilter.Add(".quizxml");


            storage = await openPicker.PickSingleFileAsync();

            if (null != storage)
            {
                // Application now has read/write access to the picked file
                fileName = storage.Name;
                filePath = storage.Path;
                loadData(quizList);
                //questions.Text = fileName + " Click Load if this is the correct File";

            }
            else
            {
                errorBox.Text = "File was not returned";
            }
        }

        async public void selection()
        {

            FileSavePicker savePicker = new FileSavePicker();
            savePicker.SuggestedStartLocation = PickerLocationId.Downloads;
            savePicker.SuggestedFileName = "quiz1";
            savePicker.DefaultFileExtension = ".quizxml";
            savePicker.FileTypeChoices.Add("QUIZ", new List<string>() { ".quizxml" });
            storage = await savePicker.PickSaveFileAsync();

            if (null != storage)
            {
                // Application now has read/write access to the picked file
                tempStorage = storage;
                filePath = storage.Path;
                fileName = storage.Name;
                saveLocation = true;
                
                SerializeXML(quizList);

            }
            else
            {
                storage = tempStorage;
                errorBox.Text = "File was not returned";
            }
        }

        async private void SerializeXML(List<quizQuest> convert)
        {

            try
            {
                var file = await storage.OpenAsync(FileAccessMode.ReadWrite);
                Stream outStream = file.AsStreamForWrite();



                xml = new DataContractSerializer(typeof(List<quizQuest>));


                xml.WriteObject(outStream, convert);

                errorBox.Text = "Saved Successfully!";
            }
            catch (IOException)
            {
                errorBox.Text = "Cannot write to the file";
            }

        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            quizQuest quest = new quizQuest();
            quest.question = multQuest.Text.ToString();
            quest.answerA = answerA.Text.ToString();
            quest.answerB = answerB.Text.ToString();
            quest.answerC = answerC.Text.ToString();
            quest.answerD = answerD.Text.ToString();
            quest.answer = finalAnswer.Text.ToString();
            quest.picture = img;

            quizList.Add(quest);

            errorBox.Text = quizList.Count.ToString() + " " + "Items Added";
            answerA.Text = "";
            answerB.Text = "";
            answerC.Text = "";
            answerD.Text = "";
            finalAnswer.Text = "";
            multQuest.Text = "";


            if (saveLocation == true || quizLoaded == true)
            {
                append(quizList);
            }
            else
            {
                saveAll.IsEnabled = true;
            }


        }

        async private void append(List<quizQuest> convert)
        {
            try
            {
                var file = await storage.OpenAsync(FileAccessMode.ReadWrite);
                outStream = file.AsStreamForWrite();

                xml.WriteObject(outStream, convert);

                await outStream.FlushAsync();
                file.Dispose();

                errorBox.Text = "Saved Successfully!";
            }
            catch (IOException)
            {
                errorBox.Text = "Cannot write to the file";
            }

        }



       async private void saveAll_Click(object sender, RoutedEventArgs e)
        {

            if (showMessage == false)
            {
                var mDialog = new MessageDialog("You only need to export once. After first export each added item will be appended to the saved file.");
                await mDialog.ShowAsync();
                showMessage = true;
            }
            else
            {
            }
            selection();




        }

        private void back_Click(object sender, RoutedEventArgs e)
        {
            this.Frame.GoBack();
        }

        private void pageRoot_Loaded(object sender, RoutedEventArgs e)
        {
            saveAll.IsEnabled = false;

            Storyboard sb = this.FindName("quizBuilderStory") as Storyboard;
            if (sb != null)
            {
                sb.Begin();
            }
        }

       async private void addImage_Click(object sender, RoutedEventArgs e)
        {
            FileOpenPicker openPicker = new FileOpenPicker();
            openPicker.ViewMode = PickerViewMode.List;
            openPicker.SuggestedStartLocation = PickerLocationId.Downloads;
            openPicker.FileTypeFilter.Add(".jpg");
            openPicker.FileTypeFilter.Add(".jpeg");
            openPicker.FileTypeFilter.Add(".png");
            openPicker.FileTypeFilter.Add(".bmp");
            storage = await openPicker.PickSingleFileAsync();

            if (null != storage)
            {

                var file = await storage.OpenAsync(FileAccessMode.Read);

                Stream inStream = file.AsStreamForRead();
               

                using (MemoryStream br = new MemoryStream())
                {
                    inStream.CopyTo(br);
                    img = br.ToArray();
                }

                // Application now has read/write access to the picked file
                //fileName = storage.Name;
                //filePath = storage.Path;
                //questions.Text = fileName + " Click Load if this is the correct File";
                errorBox.Text = "";

            }
            else
            {
                errorBox.Text = "File was not returned";
            }

        }

       private void openDeck_Click(object sender, RoutedEventArgs e)
       {

           openSelected();
       }

    }
}
